const express = require('express')
const webpack = require('webpack')
const path = require('path')
var rm = require('rimraf')
var config = require(path.join(process.cwd(), 'config'))
const merge = require('webpack-merge')
var HtmlWebpackPlugin = require('html-webpack-plugin')
const mongodb = require('mongodb').MongoClient
const dbConfig = require('./config/db')
const route = require('./page/router')
const bodyParser = require('body-parser')
global.env = process.argv.length >= 2 ? process.argv[2] : 'dev'
console.log('running on ' + global.env)

var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.all('*', function (req, resp, next) {
  resp.header('Access-Control-Allow-Origin', '*')
  resp.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild')
  resp.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
  if (req.method === 'OPTIONS') {
    resp.end('200')
  } else {
    next()
  }
})

app.use('/page', route)

app.get('/', function (req, resp) {
  // vueRender.renderToString(vm)
  rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
    if (err) {
      console.log(err)
      return
    }
    const genWebpackConfig = merge({
      entry: path.join(__dirname, 'src', 'genMain.js'),
      output: {
        path: config.build.assetsRoot,
        filename: 'dist/[name].js'
      },
      plugins: [
        new HtmlWebpackPlugin({
          filename: path.join(process.cwd(), 'dist', 'index1.html'),
          template: path.join(process.cwd(), 'src', 'api', 'genTemplates', 'index.ejs'),
          title: 'myTitle',
          param: {
            statistics: '<script>233333333</script>'
          },
          minify: {
            removeComments: true,
            collapseWhitespace: true,
            removeAttributeQuotes: true
            // more options:
            // https://github.com/kangax/html-minifier#options-quick-reference
          },
          // necessary to consistently work with multiple chunks via CommonsChunkPlugin
          chunksSortMode: 'dependency'
        })
      ]
    })
    webpack(genWebpackConfig, function (err, stats) {
      if (err) {
        console.log(err)
        return
      }
      console.log('success')
      resp.send('success')
    })
  })
})

mongodb.connect(dbConfig.dbStr, function (err, db) {
  if (err) {
    console.log(err)
    return
  }
  console.log('connect success')
  app.listen(3100, 'localhost', function () {
    console.log('end server')
    global.db = db
  })
})
